// Global singleton click sound service with a small audio pool

let pool = []
let poolIndex = 0
let isInitialized = false
let currentSrc = ''
let defaultVolume = 1

function ensurePool(size = 4) {
  if (pool.length >= size) return pool
  for (let i = pool.length; i < size; i++) {
    const el = new Audio()
    el.preload = 'auto'
    el.volume = defaultVolume
    if (currentSrc) el.src = currentSrc
    pool.push(el)
  }
  return pool
}

/**
 * Initialize click sound service with an audio src and optional pool size
 * @param {string} src
 * @param {{ size?: number, volume?: number }} [options]
 */
function init(src, options = {}) {
  if (typeof src === 'string' && src.length > 0) currentSrc = src
  if (typeof options.volume === 'number') defaultVolume = Math.min(1, Math.max(0, options.volume))
  const size = typeof options.size === 'number' && options.size > 0 ? options.size : 4
  pool = []
  poolIndex = 0
  ensurePool(size)
  isInitialized = true
}

/**
 * Play the click sound (non-blocking, uses round-robin pool item)
 * @param {number} [volume] optional per-play volume 0..1
 */
async function play(volume) {
  if (!isInitialized) return
  const items = ensurePool()
  const el = items[poolIndex]
  poolIndex = (poolIndex + 1) % items.length
  try {
    el.currentTime = 0
  } catch (_) {}
  if (typeof volume === 'number') el.volume = Math.min(1, Math.max(0, volume))
  try {
    await el.play()
  } catch (_) {
    // Autoplay may be blocked until user gesture
  } finally {
    // restore default volume if changed
    el.volume = defaultVolume
  }
}

/** Change the click src for all pool items */
function setSrc(src) {
  if (typeof src !== 'string' || !src) return
  currentSrc = src
  for (const el of pool) {
    try { el.src = src; el.load() } catch (_) {}
  }
}

/** Set default volume for subsequent plays */
function setVolume(volume) {
  defaultVolume = Math.min(1, Math.max(0, Number(volume)))
  for (const el of pool) el.volume = defaultVolume
}

export default {
  init,
  play,
  setSrc,
  setVolume,
  get initialized() { return isInitialized },
}


